<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <router-link to="/financial/receivables/batchrecord" class="mainor_tea"
              >批量对账</router-link
            >
            <el-button @click="settClick(1)">批量结算</el-button>
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="配送日期" prop="establishTime">
              <el-date-picker
                v-model="establishTime"
                type="daterange"
                class="time220"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item label="订单" prop="related_order_sn">
              <el-input
                v-model.trim="form.related_order_sn"
                placeholder="订单号/收货人/收货手机"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="商户" prop="related_order_sn">
              <el-input
                v-model.trim="form.related_order_sn"
                placeholder="商户"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-if="moredata">
                <el-form-item label="对账状态" prop="statement_status">
                  <el-select
                    v-model.trim="form.statement_status"
                    placeholder="对账状态"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(account_status_list, index) in list.account_status_list"
                      :key="index"
                      :label="account_status_list"
                      :value="parseInt(index + 1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="结算状态" prop="status">
                  <el-select
                    v-model.trim="form.status"
                    placeholder="结算状态"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(statusList, index) in list.statusList"
                      :key="index"
                      :label="statusList"
                      :value="parseInt(index+1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="结算日期" prop="createTime">
                  <el-date-picker
                    v-model="createTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                  />
                </el-form-item>
                <div class="clearfix"></div>
              </div>
            </el-collapse-transition>
            <el-form-item class="marginTop10">
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="$refs['userListFrom'].resetFields()"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_num boxdq">
          <div class="main_num_l box">
            <p>
              合计：
              <em>{{ list.paid_money }}</em>
            </p>
            <p>
              <em
                >注意：对账单未对账也可结算；批量结算时，每张订单会创建对应结算单；</em
              >
            </p>
          </div>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" :selectable="selectInit"/>
            <el-table-column label="订单号" width="200" prop="related_order_sn" />
            <el-table-column label="商户名称" width="120" prop="company_name.company_name" />
            <el-table-column label="手机号" prop="mobile" />
            <el-table-column label="下单金额" width="120" prop="order_money" />
            <el-table-column label="配送金额" width="120" prop="send_money" />
            <el-table-column label="对账金额" width="120" prop="account_money" />
            <el-table-column label="差异金额" width="120" prop="diff_money" :render-header="renderHeader_purchase"/>
            <el-table-column label="对账单号" width="120" prop="order_sn" />
            <el-table-column label="对账状态" width="120" prop="status">
              <template slot-scope="scope">{{
                list.account_status_list[scope.row.account_status]
              }}</template>
            </el-table-column>
            <el-table-column label="结算状态" width="120" prop="status">
              <template slot-scope="scope">{{
                list.statusList[scope.row.status]
              }}</template>
            </el-table-column>
            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              width="240"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <router-link :to="'/financial/receivables/see/' + scope.row.id">
                  <el-link type="success">查看</el-link>
                </router-link>
                <router-link :to="'/financial/receivables/record/' + scope.row.id" v-if="scope.row.status!=1">
                  <el-link type="warning"
                    >对账</el-link
                  >
                </router-link>
                <el-link type="primary" @click="id=scope.row.id,settClick(2)" v-if="scope.row.status!=1">结算</el-link>
                <el-link>打印</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 批量结算 -->
        <el-dialog
          title="批量结算"
          :visible.sync="settFormVisible"
          class="main_dialog dialog840"
        >
          <el-form
            :inline="false"
            :rules="rules"
            :model="info"
            class="demo-form-inline"
            ref="userListFrom1"
            label-width="0"
            key="userListFrom1"
          >
            <div class="main_table marginTop0">
              <el-table
                ref="multipleTable1"
                v-loading="listLoading"
                :data="info.data.list"
                element-loading-text="加载中"
                fit
                highlight-current-row
                key="multipleTable1"
              >
                <el-table-column label="序号">
                  <template slot-scope="scope">{{
                    scope.$index + 1
                  }}</template>
                </el-table-column>
                <el-table-column
                  label="订单号"
                  prop="related_order_sn"
                  width="220"
                  class-name="main_hei"
                />
                <el-table-column
                  label="商户名称"
                  prop="company_name.company_name"
                  width="180"
                  class-name="main_hei"
                />
                <el-table-column
                  label="下单金额"
                  prop="order_money"
                  width="120"
                  class-name="main_hei"
                />
                <el-table-column
                  label="配送金额"
                  prop="send_money"
                  width="120"
                  class-name="main_hei"
                />
                <el-table-column
                  label="对账金额"
                  prop="account_money"
                  width="120"
                  class-name="main_hei"
                />
                <el-table-column
                  label="差异金额"
                  prop="diff_money"
                  width="120"
                  class-name="main_hei"
                />
                <el-table-column
                  label="备注"
                  prop="remark"
                  width="350"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item label-width="0" label="">
                      <el-input
                        v-model.trim="scope.row.remark"
                        placeholder="备注"
                        class="wid240"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="settupmine" v-repeatClick
              >结 算</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { statement_index, statement_paid } from "@/api/financial/financialReceivables";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime } from "@/utils/index";
import rules from "@/rules/financial/financialReceivables";
import { uploadPath } from "@/api/currency";

export default {
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 上传图片
      filelist: [],
      uploadPath,
      // 时间
      parseTime,
      // 列表数据
      list: {
        list: [],
      },
      info: {
        data:{
          info:{
            order_sn:"",
            contact:"",
            mobile:"",
            address:"",
            admin_user_name:{
              name:""
            },
          },
          list:[],
          buyer:["未分拣"],
          modeList:["未分拣"],
          supplier:["未分拣"],
          pay_type_list:["未分拣"],
          typeList:["未分拣"],
        },
      },
      id:"",
      type:1,
      settFormVisible:false,
      listLoading: false,
      // 搜索
      form: {
        account_start_time: "",
        account_end_time: "",
        statement_status: null,
        status: null,
        name: "",
        order_sn: "",
        related_order_sn: "",
        start_time: "",
        end_time: "",
      },
      createTime: [],
      establishTime: [parseTime(new Date(), "{y}-{m}-{d}"),parseTime(new Date(), "{y}-{m}-{d}")],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 全选
      selectArr: [],
    };
  },
  created() {
    // 列表
    this.statement_index();
  },
  methods: {    
    // 订单差额 ？注释
    renderHeader_purchase(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "注释：差异金额=下单金额-对账金额",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    // 监听绑定全选不可勾选
    selectInit(row, index) {
      if (row.status != 1) {
        return true;
      } else {
        return false;
      }
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 结算
    settClick(type){
      if(type==1){
        if (this.selectArr.length == 0) {
          this.$message.error("请勾选订单");
          return
        }
      }
      this.type=type
      let arry=[]
      let ids=type==1?this.selectArr:[{id:this.id}]
      ids.map(e=>{
        this.list.list.data.map(p=>{
           if(e.id==p.id){
             arry.push(p)
           } 
        })
      })
      this.info.data.list=arry
      this.settFormVisible = true
    },
    settupmine() {
      this.$refs["userListFrom1"].validate((valid) => {
        if (valid) {
          this.$confirm("确定结算吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let arry=[]
              let info=JSON.parse(JSON.stringify(this.info))
              info.data.list.map(e=>{
                arry.push({id:e.id,remark:e.remark})
              })
              let data = Object.assign(
                {
                  sign: Md5(
                    objKeySort(Object.assign(apiUrl().name)) +
                      apiUrl().appsecret
                  ),
                },
                apiUrl().name,
                { list:JSON.stringify(arry) }
              );
              statement_paid(data).then((res) => {
                this.settFormVisible = false;
                if (res.errcode == 0) {
                  this.$message({
                    message: "结算成功",
                    type: "success",
                  });
                  this.statement_index();
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            })
            .catch(() => {});
        }
      });
    },
    // 搜索
    getArticleList() {
      this.statement_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    statement_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      statement_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      form.account_start_time = this.establishTime[0]
        ? this.establishTime[0]
        : "";
      form.account_end_time = this.establishTime[1]
        ? this.establishTime[1]
        : "";

      return form;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }

  .main_dialog {
    .main_xq{
      /deep/.el-form-item--small.el-form-item{
        margin-bottom: 0;
      }
    }
    
    .main_table {
      /deep/.el-table__body-wrapper {
        overflow-y: auto;
        height: 400px;
      }
      /deep/.el-table--small td {
        padding-top: 0;
      }
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 16px;
        margin-top: 16px;
        margin-right: 0;
      }
    }
    .main_xq ul li {
      width: 33.33%;
      margin-top: 5px;
      margin-bottom: 5px;
      .main_xqs{
        width: 85%;
        display: block;
        text-align: left;
        /deep/.el-input--small{
          width: 100%;
        }
      }
    }
    .footer_red{
      font-size: 16px;
      color: red;
      margin-right: 10px;
    }
  }
}
</style>
